package org.example.controller;

import com.github.pagehelper.PageInfo;
import org.example.entity.User;
import org.example.service.UserService;
import org.example.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author qiuye
 * @Date 2025年08月13日 15:12
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //    注册
    @PostMapping("register")
    public R register(@RequestParam("account") String account,
                      @RequestParam("password") String password,
                      @RequestParam("rePassword") String rePassword,
                      @RequestParam("nickname") String nickname,
                      @RequestParam("address")String address) {

        // 1. 首先检查空值
        if (account == null || account.trim().isEmpty()) {
            return R.fail("账号不能为空");
        }
        if (password == null || password.isEmpty()) {
            return R.fail("密码不能为空");
        }
        if (rePassword == null || rePassword.isEmpty()) {
            return R.fail("请确认密码");
        }

        // 2. 然后比较密码（现在不会NullPointerException了）
        if (!password.equals(rePassword)) {
            return R.fail("两次密码不一致");
        }

        try {
            int register = userService.register(account.trim(), password,nickname,address);
            if (register > 0) {
                return R.ok("注册成功");
            } else {
                return R.fail("注册失败，账号可能已存在");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息便于调试
            return R.fail("注册失败：" + e.getMessage());
        }
    }

    //    登录
    @GetMapping("login")
    public R login(String account, String password) {
        User login = userService.login(account, password);
        if (login != null) {
            return R.ok(login);
        } else
            return R.fail("登陆失败");
    }

    //    添加
    @PostMapping("add")
    public R add(@RequestBody User user) {
        int i = userService.addUser(user);
        if (i == 0) {
            return R.fail();
        } else {
            return R.ok(i);
        }
    }

    //    修改
    @PutMapping
    public R update(@RequestBody User user) {
        int i = userService.updateUser(user);
        if (i == 0) {
            return R.fail();
        } else {
            return R.ok(i);
        }
    }

    //    删除
    @DeleteMapping("{id}")
    public R delete(@PathVariable("id") int id) {
        int i = userService.deleteUser(id);
        if (i == 0) {
            return R.fail();
        } else {
            return R.ok(i);
        }
    }

    //    根据id查询
    @GetMapping("{id}")
    public R get(@PathVariable("id") int id) {
        User userById = userService.findUserById(id);
        return R.ok(userById);
    }

    //    分页查询
    @GetMapping("page")
    public R getPage(User user,
                     @RequestParam(required = false, defaultValue = "1") int page,
                     @RequestParam(required = false, defaultValue = "3") int size) {
        PageInfo<User> users = userService.findUsers(user, page, size);
        return R.ok(users);
    }

    //分页级联问题表
    @GetMapping("jilian")
    public R jilian(User user,
                    @RequestParam(required = false, defaultValue = "1") int pageNum,
                    @RequestParam(required = false, defaultValue = "3") int pageSize) {
        PageInfo<User> userPageInfo = userService.selectUserAndQuestion(user, pageNum, pageSize);
        return R.ok(userPageInfo);
    }

    //    修改密码
    @PutMapping("updatePassword")
    public R updatePassword(@RequestParam int userId,
                            @RequestParam String newPassword,
                            @RequestParam String confirmPassword) {
        System.out.println("接收参数 - userId: " + userId + ", newPassword: " + newPassword + ", confirmPassword: " + confirmPassword);

        // 参数验证
        if (userId <= 0) {
            return R.fail("用户ID无效");
        }
        if (newPassword == null || newPassword.isEmpty()) {
            return R.fail("新密码不能为空");
        }
        if (confirmPassword == null || confirmPassword.isEmpty()) {
            return R.fail("确认密码不能为空");
        }
        if (!newPassword.equals(confirmPassword)) {
            return R.fail("两次密码不一致");
        }

        try {
            int result = userService.updatePassword(userId, newPassword);
            if (result > 0) {
                return R.ok("密码修改成功");
            } else {
                return R.fail("密码修改失败，用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("系统错误，请稍后重试");
        }
    }

    //    修改手机号
    @PutMapping("updatePhone")
    public R updatePhone(Integer userId,  String phone){
        if(phone.length()!=11){
            return R.fail();
        }

        int i = userService.updatePhone(userId, phone);
        if (i == 0) {
            return R.fail();
        }else {
            return R.ok();
        }
    }

}
